/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/sort-comp */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Form, DatePicker } from 'antd';
import StandardTable from '@/components/StandardTable';
import DownloadBar from '@/components/DownloadBar';
import { dateCalendar, setLStorage, getLStorage } from '@/utils/utils';
import moment from 'moment/moment';
import { debounce } from 'lodash';
import KbSelect from '@/components/KbSelect';
import { getReportListType, getReportType } from '@/services/report';
import styles from './index.less';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@connect(({ report, loading, user, setting }) => ({
  userType: setting.options.key,
  user_info: user.currentUser.user_info,
  report,
  getting: loading.effects['report/getReport'],
}))
@Form.create()
class DownReport extends Component {
  regeneration = debounce(
    id => {
      const { dispatch, userType, user_info } = this.props;
      const { report_type } = this.state;
      const payload = {
        id,
        classify: report_type,
      };
      if (userType != 'yz') {
        payload.branch_id = user_info.branchId;
      }
      dispatch({
        type: 'report/regeneration',
        payload,
        then: res => {
          if (res.code == 0) {
            this.onSearch();
          }
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    const { user_info = {} } = this.props;
    // 报表类型
    this.sKey = `REPORT_TYPE_${user_info.phone}`;

    this.columns = [
      {
        title: '导出时间',
        dataIndex: 'create_time',
        align: 'center',
        render: dateCalendar,
      },
      {
        title: '报表类型',
        dataIndex: 'file_title',
        align: 'center',
      },
      {
        title: '报表内容',
        dataIndex: 'file_name',
        align: 'center',
      },
      {
        title: '报表状态',
        dataIndex: 'status',
        align: 'center',
        render: (text, { msg }) => {
          switch (text) {
            case '-1':
              return <span style={{ color: 'red' }}>{msg || '生成失败'}</span>;
            case '0':
            case '1':
              return <span>生成中</span>;
            case '2':
              return <span>已生成</span>;
            default:
              return '-';
          }
        },
      },
      {
        title: '操作人',
        dataIndex: 'operator',
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'id',
        align: 'center',
        render: (id, record) => {
          const { file_path, status, msg = '' } = record;
          if (status == 2 && file_path) {
            return (
              <DownloadBar href={`${file_path}`}>
                <Button size="small" ghost type="primary" icon="download">
                  下载
                </Button>
              </DownloadBar>
            );
          }
          if (msg.includes('暂无数据')) {
            return '';
          }
          if (status == '-1') {
            return <a onClick={() => this.regeneration(id)}>重新生成</a>;
          }
          return '';
        },
      },
    ];
    this.state = {
      startDate: moment()
        .startOf('day')
        .subtract(6, 'days'),
      endDate: moment()
        .startOf('day')
        .subtract(0, 'days'),
    };
    this.regeneration = this.regeneration.bind(this);
  }

  componentDidMount() {
    this.onSearch();
  }

  disabledDate = current =>
    current &&
    current >
      moment()
        .endOf('day')
        .subtract(0, 'days');

  dataClick = data => {
    const { form } = this.props;
    const setFieldsValueDate = {
      startDate: moment()
        .startOf('day')
        .subtract(data, 'days'),
      endDate: moment()
        .endOf('day')
        .subtract(data == 1 ? 1 : 0, 'days'),
    };
    form.setFieldsValue({
      date: [setFieldsValueDate.startDate, setFieldsValueDate.endDate],
    });
  };

  onSearch = click => {
    const {
      form: { validateFields },
      dispatch,
      user_info,
      userType,
    } = this.props;
    validateFields((err, fieldsValues) => {
      if (err) return;
      const values = { ...fieldsValues };
      const { date, report_type } = fieldsValues;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start_date = start;
        values.end_date = end;
        delete values.date;
      }
      if (click) {
        setLStorage(this.sKey, report_type);
      }
      this.setState({
        report_type,
      });
      values.classify = report_type;
      delete values.report_type;
      if (userType != 'yz') {
        values.branch_id = user_info.branchId;
      }
      dispatch({
        type: 'report/getReport',
        payload: {
          ...values,
        },
      });
    });
  };

  onReportTypeChange = () => {
    const { form } = this.props;
    const { setFieldsValue } = form;
    setFieldsValue({
      file_type: 'all',
    });
  };

  render() {
    const {
      getting,
      report: { data },
      form: { getFieldDecorator, getFieldsValue },
      userType,
    } = this.props;
    const { startDate, endDate } = this.state;
    const list = { list: data };
    const isYjy = userType == 'yjy';
    const initReportType = isYjy ? 'gp' : getLStorage(this.sKey) || 'inn';
    const { report_type } = getFieldsValue();

    return (
      <>
        <Form layout="inline">
          <FormItem>
            <a className={styles.select_date} onClick={() => this.dataClick(0)}>
              今天
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(1)}>
              昨天
            </a>
            <a className={styles.select_date} onClick={() => this.dataClick(6)}>
              近7日
            </a>
          </FormItem>
          <FormItem>
            {getFieldDecorator('date', {
              initialValue: [startDate, endDate],
            })(
              <RangePicker
                style={{ width: '280px' }}
                placeholder={['开始日期', '结束日期']}
                disabledDate={this.disabledDate}
              />,
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('report_type', {
              initialValue: initReportType,
            })(
              <KbSelect
                style={{ width: 100 }}
                request={() => getReportType()}
                format="option*content"
                onChange={this.onReportTypeChange}
              />,
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('file_type', {
              initialValue: 'all',
            })(
              <KbSelect
                style={{ width: 220 }}
                request={() => getReportListType({ type: report_type })}
                dependency={report_type}
                format="option*content"
              />,
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" onClick={this.onSearch.bind(this, true)}>
              查询
            </Button>
          </FormItem>
        </Form>
        <StandardTable
          data={list}
          columns={this.columns}
          loading={getting}
          hasPagination={false}
          rowKey="id"
        />
      </>
    );
  }
}

export default DownReport;
